package com.yao.component.circle;

import android.annotation.TargetApi;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.BitmapDrawable;
import android.os.Build;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.SpannableStringBuilder;
import android.text.TextPaint;
import android.text.method.LinkMovementMethod;
import android.text.style.ClickableSpan;
import android.text.style.ImageSpan;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.toolbox.ImageLoader;
import com.android.volley.toolbox.NetworkImageView;
import com.hp.hpl.sparta.Text;
import com.hzl.DensityUtil;
import com.hzl.UserInfoBean;
import com.yao.component.circle.dataobject.CircleProfile;
import com.yao.component.circle.dataobject.Post;
import com.yao.component.circle.dataobject.Message;
import com.yao.sdk.net.NetConstant;
import com.yao.sdk.util.Utils;
import com.yao.sdk.widget.CollapsibleTextView;
import com.yao.sdk.widget.ExtGridLayoutManager;
import com.yzf.TimeUtil;
import com.yzf.bean.GroupBean;

import java.util.ArrayList;

/**
 * Circle列表的数据适配器
 */
public class CircleAdapter extends RecyclerView.Adapter<CircleAdapter.ViewHolder> {
    private CircleDataSource dataSource;

    private CircleStyle circleStyle;

    private CircleView circleView;

    private ImageLoader imageLoader;
    private RelativeLayout pop_left;
    private PopupWindow popupWindow;
    public CircleAdapter() {
    }

    private View contentView;

    public void setImageLoader(ImageLoader imageLoader) {
        this.imageLoader = imageLoader;
    }

    public void setCircleView(CircleView circleView) {
        this.circleView = circleView;
    }

    // 设置Circle列表要显示的数据源
    public void setDataSource(CircleDataSource dataSource) {
        this.dataSource = dataSource;
    }

    public void setCircleStyle(CircleStyle circleView) {
        this.circleStyle = circleView;
    }

    /**
     * 通过ViewHolder可以访问每个item的所有控件
     */
    public static class ViewHolder extends RecyclerView.ViewHolder {
        //绑定每个CircleItem的控件引用到ViewHolder
        public ImageView icon;
        public TextView name;
        public TextView className;
        public TextView createTime;
        public RecyclerView photoList;
        public CollapsibleTextView content;
        public RelativeLayout commentWrapper;
        public MessageView messageView;
        public ImageButton praiseAdd;
        public ImageButton commentAdd;
        public TextView itemDel;
        public ImageView popCommit;
        public TextView createAdd;
        public TextView tv_remind;
        public ImageView img_label;
        public RelativeLayout rl_like;
        public TextView like_label;
        public View xian;
        PhotoListAdapter photoListAdapter;


        public ViewHolder(View v, ImageLoader imageLoader) {
            super(v);
            icon = (ImageView)v.findViewById(R.id.me_icon);
            name = (TextView)v.findViewById(R.id.info_name);
            className = (TextView)v.findViewById(R.id.info_classname);
            createTime = (TextView)v.findViewById(R.id.createTime);
            content = (CollapsibleTextView)v.findViewById(R.id.info_content);
            photoListAdapter = new PhotoListAdapter();
            photoList = (RecyclerView) v.findViewById(R.id.photo_list);
            photoList.setLayoutManager(new ExtGridLayoutManager(v.getContext(), 3));
            photoList.setAdapter(photoListAdapter);


            content.setButtonText(v.getContext().getString(R.string.desc_shrink), v.getContext().getString(R.string.desc_spread));
            praiseAdd = (ImageButton)v.findViewById(R.id.praise_add);
            commentWrapper = (RelativeLayout)v.findViewById(R.id.comment_wrapper);
            commentAdd = (ImageButton)v.findViewById(R.id.comment_add);
            messageView = (MessageView)v.findViewById(R.id.comment_list);
            rl_like = (RelativeLayout) v.findViewById(R.id.rl_like);
            like_label = (TextView) v.findViewById(R.id.like_label);
            itemDel = (TextView)v.findViewById(R.id.btn_del);
            popCommit = (ImageView) v.findViewById(R.id.pop_commit);
            createAdd = (TextView) v.findViewById(R.id.createAdd);
            tv_remind = (TextView) v.findViewById(R.id.tv_remind);
            img_label = (ImageView) v.findViewById(R.id.img_label);
            xian = v.findViewById(R.id.xian);


        }
    }

    private void styleConfig(ViewHolder vh) {
        if (circleStyle.getItemNameTextColor() != CircleStyle.INVALID) {
            vh.name.setTextColor(circleStyle.getItemNameTextColor());
        }
        if (circleStyle.getItemContentOptTextColor() != CircleStyle.INVALID) {
            vh.content.setOptTextColor(circleStyle.getItemContentOptTextColor());
        }
        if (circleStyle.getPraiseButtonSelector() != CircleStyle.INVALID) {
            vh.praiseAdd.setBackgroundResource(circleStyle.getPraiseButtonSelector());
        }
    }

    // 创建每个Item的视图 (invoked by the item_circle manager)
    @Override
    public CircleAdapter.ViewHolder onCreateViewHolder(ViewGroup parent,
                                                   int viewType) {
        //创建circleItem所对应的控件
        View v = LayoutInflater.from(parent.getContext())
                .inflate(R.layout.item_circle, parent, false);
        // set the view's size, margins, paddings and item_circle parameters
        ViewHolder vh = new ViewHolder(v, imageLoader);
        styleConfig(vh);
        return vh;
    }



    // Replace the contents of a view (invoked by the item_circle manager)
    @Override
    public void onBindViewHolder(final ViewHolder holder, int position) {

        final Post post = dataSource.getCachedPost().get(position);
        post.setIndex(position);
        holder.icon.setImageResource(R.drawable.icon0001);
//         //设置icon
//        final String iconUrl = NetConstant.BASE_IMAGE_URL + post.getIconUrl();
//        if (Utils.isEmpty(post.getIconUrl())) {
//            holder.icon.setImageResource(R.drawable.default_avatar_img);
//        } else if (!Utils.isEmpty(iconUrl)) {
//            Picasso.with(holder.icon.getContext()).load(iconUrl).placeholder(R.drawable.default_avatar_img).resize(50, 50)
//                    .centerCrop().into(holder.icon);
//        }
//        holder.icon.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//                Intent intent = new Intent(v.getContext(), PictureBrowseActivity.class);
//                ArrayList list = new ArrayList();
//                list.add(iconUrl);
//                intent.putStringArrayListExtra(PictureBrowseActivity.IMAGE_URL_LIST, list);
//                intent.putExtra(PictureBrowseActivity.IMAGE_URL_POSITION, 0);
//                v.getContext().startActivity(intent);
//            }
//        });
        //弹出pop点赞和评论
        holder.popCommit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showPopupWindow(holder.popCommit,post,holder);
            }
        });

        //点赞
        String like_name = "";
        ArrayList<String> like_list = post.getLike_list();
        if (!Utils.isEmpty(like_list)){
            // 构造多个超链接的html, 通过选中的位置来获取用户名
            StringBuilder sbBuilder = new StringBuilder();
            holder.rl_like.setVisibility(View.VISIBLE);
            for (int i = 0; i < like_list.size(); i++) {
                String name = like_list.get(i);
                like_name = like_name + name + ",";
                sbBuilder.append(name + ",");
            }
//            String substring = like_name.substring(0,like_name.length() - 1);
            String likeUsers = sbBuilder.substring(0, sbBuilder.lastIndexOf(",")).toString();
            holder.like_label.setMovementMethod(LinkMovementMethod.getInstance());
            holder.like_label.setText(addClickablePart(likeUsers,holder.like_label), TextView.BufferType.SPANNABLE);

//            holder.like_label.setText(substring);
        }else {
            holder.rl_like.setVisibility(View.GONE);
        }

        holder.name.setText(post.getPosterName());
        holder.className.setText(post.getClassName());
        //设置显示的时间
        holder.createTime.setText(TimeUtil.dateDiff(post.getCreateTime()));
        //是否定位
        if (!Utils.isEmpty(post.getAddress())){
            holder.createAdd.setVisibility(View.VISIBLE);
            holder.createAdd.setText(post.getAddress());
        }else {
            holder.createAdd.setVisibility(View.GONE);
        }
        //是否有提醒谁看
        final ArrayList<UserInfoBean> remindList = post.getRemindList();
        String userName = "";
        if (!Utils.isEmpty(remindList)){
            holder.tv_remind.setVisibility(View.VISIBLE);
            for (int i = 0; i < remindList.size(); i++) {
                userName = userName + remindList.get(i).getUserName() + ",";
            }
            String remindname = userName.substring(0, userName.length() - 1);
            holder.tv_remind.setText("提到了:" + remindname);
        }else {
            holder.tv_remind.setVisibility(View.GONE);
        }
        //是否带标签
        final ArrayList<GroupBean> groupList = post.getGroupList();
        if (!Utils.isEmpty(groupList)){
            holder.img_label.setVisibility(View.VISIBLE);
            holder.img_label.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Intent intent = new Intent(v.getContext(),VisibleFriendActivity.class);
                    intent.putExtra("remindList",remindList);
                    intent.putExtra("goupList",groupList);
                    v.getContext().startActivity(intent);
                }
            });
        }else {
            holder.img_label.setVisibility(View.GONE);
        }

        // 如果内容过长，需要设置是否显示全文
        holder.content.setContent(post.getContent());
        holder.photoList.setVisibility(View.GONE);
        if (!Utils.isEmpty(post.getCirclePhoto())) {


               /* if (photoList.size() <= 3) {
                    holder.photoList.setMinimumHeight(90);
                } else {
                    holder.photoList.setMinimumHeight(200);
                }*/
                holder.photoListAdapter.setData(post.getCirclePhoto());
                holder.photoList.setVisibility(View.VISIBLE);
        }

        //设置删除按钮
        if (circleView.getDataSource().getProfile().getUserId().equals(post.getUserId())) {
            holder.itemDel.setVisibility(View.VISIBLE);
        } else {
            holder.itemDel.setVisibility(View.GONE);
        }
        holder.itemDel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                MessageEditor.getInstance().setCircleItemIndex(post.getIndex());
                circleView.showCommentDelWindow(CircleView.MODE_DELETE_POST);
            }
        });


        // 设置评论列表
        holder.messageView.setCircleView(circleView);

        if (Utils.isEmpty(post.getMessageList()) && Utils.isEmpty(post.getLike_list()) ) {
            holder.commentWrapper.setVisibility(View.GONE);
            holder.xian.setVisibility(View.GONE);
        }else if ( Utils.isEmpty(post.getMessageList()) && !Utils.isEmpty(post.getLike_list()) ){
            holder.commentWrapper.setVisibility(View.VISIBLE);
            holder.xian.setVisibility(View.GONE);
        }else {
            holder.commentWrapper.setVisibility(View.VISIBLE);
            holder.messageView.refreshData(post);
            holder.xian.setVisibility(View.VISIBLE);
        }

    }

    private SpannableStringBuilder addClickablePart(String str, final TextView like_label) {
        // 第一个赞图标
//        ImageSpan span = new ImageSpan(like_label.getContext(), R.drawable.like_little_select);
        SpannableString spanStr = new SpannableString(" ");
        spanStr.setSpan(null, 0, 1, Spannable.SPAN_INCLUSIVE_EXCLUSIVE);

        SpannableStringBuilder ssb = new SpannableStringBuilder(spanStr);
        ssb.append(str) ;

        String[] likeUsers = str.split(",");

        if (likeUsers.length > 0) {
            // 最后一个
            for (int i = 0; i < likeUsers.length; i++) {
                final String name = likeUsers[i];
                final int start = str.indexOf(name) + spanStr.length();
                ssb.setSpan(new ClickableSpan() {

                    @Override
                    public void onClick(View widget) {
                        Toast.makeText(like_label.getContext(), name,
                                Toast.LENGTH_SHORT).show();
                    }

                    @Override
                    public void updateDrawState(TextPaint ds) {
                        super.updateDrawState(ds);
                         ds.setColor(Color.parseColor("#09bb07")); // 设置文本颜色
                        // 去掉下划线
                        ds.setUnderlineText(false);
                    }

                }, start, start + name.length(), 0);
            }
        }
//        return ssb.append("等"
//                + likeUsers.length + "个人赞了您.");
        return ssb;
    } // end of addClickablePart

    @TargetApi(Build.VERSION_CODES.KITKAT)
    private void showPopupWindow(View v, final Post post, final ViewHolder holder) {
        // 一个自定义的布局，作为显示的内容
        if (popupWindow == null){
            contentView = LayoutInflater.from(v.getContext()).inflate(
                    R.layout.popu_item, null);


            popupWindow = new PopupWindow(contentView,
                RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT, true);
            contentView.measure(View.MeasureSpec.UNSPECIFIED, View.MeasureSpec.UNSPECIFIED);
            popupWindow.setFocusable(true);
            popupWindow.setOutsideTouchable(true);  //设置点击屏幕其它地方弹出框消失
            popupWindow.setBackgroundDrawable(new BitmapDrawable());
        }
        int popupWidth = contentView.getMeasuredWidth();
        int popupHeight =  contentView.getMeasuredHeight();
        int[] location = new int[2];
        v.getLocationOnScreen(location);
        popupWindow.showAtLocation(v, Gravity.NO_GRAVITY, location[0]-popupWidth,
                location[1]-popupHeight/8);
        final TextView tv_like = (TextView) contentView.findViewById(R.id.tv_like);
        final ArrayList<String> like_list = post.getLike_list();
        if (post.isPraised() == true){
            tv_like.setText("取消");
        }else {
            tv_like.setText("赞");
        }
        // 设置按钮的点击事件
        contentView.findViewById(R.id.pop_left).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // 设置点赞按钮
                String posterName = post.getId();
                CircleProfile circleProfile = dataSource.getProfile();
                String name = circleProfile.getName();
                if (post.isPraised() == false) {
                    like_list.add(name);
                    post.setPraised(true);
                } else {
                    post.setPraised(false);
                    for (int i = 0; i < like_list.size(); i++) {
                        if (like_list.get(i).equals(name)){
                            like_list.remove(i);
                        }
                    }
                }
                circleView.refresh();
                popupWindow.dismiss();
            }
        });

        contentView.findViewById(R.id.pop_right).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // 设置回复按钮
//                holder.commentAdd.setOnClickListener(new View.OnClickListener() {
//                    @Override
//                    public void onClick(View v) {
                        MessageEditor.getInstance().setCircleItemIndex(post.getIndex());
                        MessageEditor.getInstance().setMessageType(Message.TYPE_COMMENT);
                        circleView.showEditWindow(v.getContext().getString(R.string.circle_reply) + post.getPosterName() + ":");

//                    }
//                });
                popupWindow.dismiss();
            }
        });

    }

    // 获取Circle数据的item个数
    @Override
    public int getItemCount() {
        return dataSource.getCachedPost().size();
    }



}

